package org.neusoft.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.security.Key;
import java.util.Date;

@Service
public class JwtService {

    @Value("${application.jwt.secret-key}")
    private String secretKey;

    @Value("${application.jwt.expire-time}")
    private Long expiration;

    public String toToken(String userId) {
        return Jwts.builder()
                .setSubject(userId)
                .signWith(getSignKey())
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
//                .claim("email",userName)
                .compact();
    }

    public String getSub(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    .setSigningKey(getSignKey())
                    .build()
                    .parseClaimsJws(token);
            return claimsJws.getBody().getSubject();
        } catch (JwtException e) {
            return null;
        }
    }

    /**
     * 验证令牌是否有效
     *
     * @param token 要验证的令牌字符串
     * @return 如果令牌有效，则返回true；否则返回false
     * @throws JwtException 如果解析令牌时发生异常，则抛出此异常
     */
    public boolean validateToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    .setSigningKey(getSignKey())
                    .build()
                    .parseClaimsJws(token);

            Date now = new Date(System.currentTimeMillis());
            Date expiration = claimsJws.getBody().getExpiration();
            return expiration.after(now);
        } catch (JwtException e) {
            return false;
        }
    }

    private Key getSignKey() {
        return Keys.hmacShaKeyFor(secretKey.getBytes());
    }
}